package 剑指offer;

public class _05替换空格 {
    public String replaceSpace(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == ' '){
                count++;
            }
        }

        int newLength = s.length() + 2 * count;
        int oldIndex = s.length() - 1;
        int newIndex = newLength - 1;
        char[] newStr = new char[newLength];
        while (oldIndex >= 0 && newIndex >= 0){
            if(s.charAt(oldIndex) == ' '){
                newStr[newIndex--] =  '0';
                newStr[newIndex--] =  '2';
                newStr[newIndex--] =  '%';
                --oldIndex;
            }else {
                newStr[newIndex--] =  s.charAt(oldIndex);
                --oldIndex;
            }
        }
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < newLength; i++) {
            sb.append(newStr[i]);
        }
        return sb.toString();
    }
}
